import {
    SetTaskScore,
    PostWorksShare,
    GetEditVersion,
} from "~/api";
import { aesEncrypt } from "~/utils/encrypt.js";

const jumpUrl = (url) => {
    const pageStore = usePageStore();
    window.open(url, pageStore.isMobile ? "_self" : "_blank");
};

export const useContent = () => {
    const pageStore = usePageStore();
    const dialogStore = useDialogStore();
    const userStore = useUserStore();

    const onComment = async (item) => {
        if (userStore.isLogin) {
            dialogStore.isCommentListDialogVisible = true;
            dialogStore.commentWorkId = item.id;
        } else {
            LoginModal();
        }
    };

    const onShare = async (item, type) => {
        dialogStore.isShareTemplateDialogVisible = true;
        let url = GetWorkLink(item.url, type);
        dialogStore.shareUrl = url;
        dialogStore.shareName = item.name;

        await SetTaskScore({
            code: 1004,
            _id: item.id,
        });

        const res = await PostWorksShare({
            work_id: item.id,
        });

        item.share = res.data;
    };

    const onPreview = (item, type) => {
        let url = GetWorkLink(item.url, type);
        jumpUrl(url);
    };

    const onMakeSame = async (item, type) => {
        const dialogStore = useDialogStore();
        if (userStore.isLogin) {
            if (pageStore.isMobile) {
                const res = await GetEditVersion();
                if (localStorage.getItem("editor_version") !== res.data) {
                    localStorage.setItem("editor_version", res.data);
                    dialogStore.isEditorUpdateTipsDialogVisible = true;
                } else {
                    Message().warning("请在电脑端网站打开！网址www.ykjhr.com");
                }
            } else {
                const search =
                    "tid=" +
                    item.templates_id +
                    "&type=template&uid=" +
                    userStore.userInfo.id;

                let origin = GetTemplateLink3(type);

                const newUrl = `https://${origin}/?${aesEncrypt(search)}`;


                jumpUrl(newUrl);
            }
        } else {
            let origin = GetTemplateLink3(type);

            LoginModal(
                true,
                pageStore.isMobile
                    ? {}
                    : {
                        url: `https://${origin}/`,
                        search: "tid=" + item.templates_id + "&type=template",
                        params: ["uid"],
                        encrypt: true,
                    },
                {},
                !pageStore.isMobile
            );
        }
    };

    return {
        onShare,
        onPreview,
        onComment,
        onMakeSame,
    };
};
